const { updateUserInfo } = require('../../utils/info')
Page({
  data: {
    userInfo: null,
    phoneNumber: '',
    token: ''
  },
  onShow() {
    const userInfo = wx.getStorageSync('userInfo')
    const phoneNumber = wx.getStorageSync('phoneNumber')
    const token = wx.getStorageSync('token')
    this.setData({ userInfo, phoneNumber, token })
  },
  onSetting() {
    wx.showToast({ title: '设置功能开发中', icon: 'none' })
  },
  onSignIn() {
    wx.navigateTo({ url: '/pages/signin/signin' })
  },
  onRecord() {
    wx.navigateTo({ url: '/pages/video-record/video-record' })
  },
  onContact() {
    wx.showModal({
      title: '联系客服',
      content: '请添加客服微信：pinxuango',
      showCancel: false
    })
  },
  onLogout() {
    wx.removeStorageSync('token')
    wx.removeStorageSync('userInfo')
    wx.showToast({ title: '已退出登录', icon: 'success' })
    this.setData({ token: '', userInfo: null })
    // 断开全局socket
    const app = getApp();
    if (app.socket) {
      try {
        app.socket.disconnect();
      } catch (e) {
        console.warn('socket disconnect error', e);
      }
      app.socket = null;
      app.globalData.isSocketConnect = false;
    }
    setTimeout(() => {
      wx.redirectTo({ url: '/pages/login/login' })
    }, 500)
  },
  onGetUserInfo() {
    wx.getUserProfile({
      desc: '用于完善会员资料',
      success: (res) => {
        const userInfo = res.userInfo;
        this.setData({ userInfo });
        // 更新存储用户信息到缓存
        wx.setStorageSync('userInfo', userInfo)
        // TODO: Upload userInfo to your server
        console.log('User Info:', userInfo);
        updateUserInfo({avatarUrl: userInfo.avatarUrl, sex: userInfo.gender})
      },
      fail: (err) => {
        console.error('getUserProfile failed:', err);
        wx.showToast({ title: '获取用户信息失败', icon: 'none' });
      }
    });
  },
  onIntegralRecord() {
    wx.navigateTo({ url: '/pages/integral-record/integral-record' })
  },
  onMyTask() {
    wx.navigateTo({ url: '/pages/task/my-task/my-task' });
  },
  onTaskSquare() {
    wx.navigateTo({ url: '/pages/task/task-square/task-square' });
  },
  onMyCheckIn() {
    wx.navigateTo({ url: '/pages/task/my-check-in/my-check-in' });
  },
  onProjectDesc() {
    wx.navigateTo({ url: '/pages/project-desc/project-desc' });
  },
  onMessageManage() {
    wx.navigateTo({ url: '/pages/message-manage/message-manage' });
  },
  onGoMySetting() {
    wx.navigateTo({ url: '/pages/my-setting/my-setting' });
  }
}) 